package com.hrsaas.ext.spider.test.handler;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.hrsaas.ext.spider.client.HeaderFactory;
import com.hrsaas.ext.spider.core.CookieStore;
import com.hrsaas.ext.spider.core.HttpClient;
import com.hrsaas.ext.spider.test.domain.JGSignBean;
import com.hrsaas.ext.spider.test.mybatis.model.ResumeSpider;
import com.hrsaas.ext.spider.test.mybatis.util.SpiderFactory;

import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;

/**
 * <p>
 * 功能：模拟登录,并请求必要的url获取相应的cookie,大概有5个请求才会下发必要的cookie
 * <p>
 * @author wangxiaoliang@kanzhun.com
 *
 * 2018年8月7日
 */
public class LoginLGHandler extends LGResponseHandler<String> {
	
	private final ResumeSpider model;
	
	public LoginLGHandler(ResumeSpider model) {
		this.model = model;
	}
	
	public ResumeSpider getModel() {
		return model;
	}

	@Override
	protected boolean receive(HttpResponseStatus status, CookieStore cookieStore, 
			HttpHeaders headers, String response) {
		if (HttpResponseStatus.OK.equals(status)) {
			int _token = response.indexOf("X_Anti_Forge_Token");
			int _code = response.indexOf("X_Anti_Forge_Code");
			if (_token != -1 && _code != -1) {
				String forge_Token = response.substring(_token + 22,_token + 22 + 36);
				String forge_Code  = response.substring(_code + 21, _code + 21 + 8);
				// 传递header
				headers.clear();
				headers.add("X-Anit-Forge-Token", forge_Token);
				headers.add("X-Anit-Forge-Code", forge_Code);
				return true;
			}
		}
		return false;
	}

	/* 
	 * 发起真正的登录接口
	 */
	@Override
	protected void next(HttpClient client, String object, CookieStore cookieStore,
			HttpHeaders headers) {
		final HttpHeaders loginHeaders = headers;

		String redirect_url = getRedirectUrl();
		String collects_url = "https://a.lagou.com/collect?v=1&_v=j31&a=957032623&t=pageview&_s=1&dl=" + URLEncoder.encode(redirect_url) + "&ul=en-us&de=UTF-8&dt=%E6%89%BE%E5%B7%A5%E4%BD%9C-%E4%BA%92%E8%81%94%E7%BD%91%E6%8B%9B%E8%81%98%E6%B1%82%E8%81%8C%E7%BD%91-%E6%8B%89%E5%8B%BE%E7%BD%91&sd=24-bit&sr=1920x1080&vp=316x897&je=0&_u=MEAAAAQBK~&jid=733374910&cid=1770634916.1535613098&tid=UA-41268416-1&_r=1&z=982348760";
		
		client.get().setURL(collects_url)
			.addHeaders(HeaderFactory.COLLECTIOINS)
			.addReferer(redirect_url)
			.addCookieStore(cookieStore)
			.execute(new LGResponseHandler<Object>() {
				@Override
				protected void next(HttpClient client, Object object, CookieStore cookieStore,HttpHeaders headers) {
					client.post().setURL("https://passport.lagou.com/login/login.json")
						.addHeaders(HeaderFactory.LOGINJSON)
						.addHeaders(loginHeaders)
						.addReferer(redirect_url)
						.addCookieStore(cookieStore)
						.addQueryPairs(getArgs())
						.execute(new LGResponseHandler<JGSignBean>() {
							@Override
							protected boolean receive(HttpResponseStatus status, CookieStore cookieStore, 
									HttpHeaders respheaders, JGSignBean gson) {
								if (gson == null || gson.getState() != 1) {
									return false;
								}
								return true;
							}
							@Override
							protected void next(HttpClient client, JGSignBean object,CookieStore cookieStore,HttpHeaders reqheaders) {
								client.get().setURL("https://passport.lagou.com/grantServiceTicket/grant.html")
									.addHeaders(HeaderFactory.GRANT)
									.addReferer(redirect_url)
									.addCookieStore(cookieStore)
									.execute(new LGResponseHandler<String>() {
										@Override
										protected boolean receive(HttpResponseStatus status, CookieStore cookieStore, HttpHeaders headers,
												String response) {
											if (HttpResponseStatus.OK.equals(status)) {
												int _token = response.indexOf("X_Anti_Forge_Token");
												int _code = response.indexOf("X_Anti_Forge_Code");
												if (_token != -1 && _code != -1) {
													String forge_Token = response.substring(_token + 22,_token + 22 + 36);
													String forge_Code  = response.substring(_code + 21, _code + 21 + 36);
													// 传递header
													headers.clear();
													headers.add("x-anit-forge-token", forge_Token);
													headers.add("x-anit-forge-code", forge_Code);
													return true;
												}
											}
											return false;
										}
										@Override
										protected void next(HttpClient client, String object, CookieStore cookies,
												HttpHeaders headers) {
											// 登录并跳转成功，将用户的cookie及header保存入库
											updateModel(headers, cookies);
											reload(client, cookieStore, headers);
										}
									});
							}
					});
				}
		});
	}

	/**
	 * 简历拉取入口
	 * @param client
	 * @param cookieStore
	 * @param loginHeaders
	 */
	protected void reload(HttpClient client, CookieStore cookieStore, HttpHeaders loginHeaders) {
		// 简历拉取入口
		new LGCoreResumeHandler(client, cookieStore, loginHeaders).start();
	}
	
	private Map<String, String> getArgs() {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("isValidate", "true");
		paramMap.put("username", model.getUsername());
		paramMap.put("password", encryptPassword(model.getPassword()));
		paramMap.put("request_form_verifyCode", "");
		paramMap.put("submit", "");
		return paramMap;
	}
	
	/**
	 * 密码加密
	 * @param password
	 * @return
	 */
	String encryptPassword(String password) {
		return MD5Utils.md5EncodeStr("veenike" + MD5Utils.md5EncodeStr(password) + "veenike");
	}
	
	/**
	 * 更新到数据库
	 * @param loginHeaders
	 * @param cookies
	 */
	private void updateModel(final HttpHeaders loginHeaders, CookieStore cookies) {
		model.setCookies(cookies.toString());
		model.setHeaders(HeaderFactory.toString(loginHeaders));
		SpiderFactory.update(model);
	}
	
}
